package cn.com.demo.filter;

import cn.com.demo.config.MyTokenConfig;
import cn.com.demo.util.LocalCache;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.util.StringUtils;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

public class MyTokenAuthFilter extends BasicAuthenticationFilter {
    MyTokenConfig myTokenConfig;
    public MyTokenAuthFilter(AuthenticationManager authenticationManager, MyTokenConfig myTokenConfig) {
        super(authenticationManager);
        this.myTokenConfig = myTokenConfig;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        // 获取认证成功的用户授权信息
        String token = request.getHeader(myTokenConfig.getTokenConfigProperties().getHeadName());
        if(!StringUtils.isEmpty(token)) {
            String userName = myTokenConfig.getUserName(token);
            List<GrantedAuthority> authorities = (List<GrantedAuthority>) LocalCache.get(userName);
            if(authorities != null) {
                // 放置权限到security上下文中
                UsernamePasswordAuthenticationToken auths = new UsernamePasswordAuthenticationToken(userName, token, authorities);
                SecurityContextHolder.getContext().setAuthentication(auths);
            }
        }
        // 过滤链需要继续向下
        chain.doFilter(request,response);
    }

    @Override
    protected void onSuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, Authentication authResult) throws IOException {
        System.out.println("鉴权通过。。。。");
    }

    @Override
    protected void onUnsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException {
        System.out.println("鉴权失败");
    }
}
